package com.winsdom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.winsdom.dto.CustomerBillingHeaderCreateDTO;
import com.winsdom.dto.CustomerBillingHeaderDTO;
import com.winsdom.entity.CustomerBillingHeader;
import com.winsdom.entity.vo.CustomerBillingHeaderVo;
import com.winsdom.mapper.CustomerBillingHeaderMapper;
import com.winsdom.service.ICustomerBillingHeaderService;
import com.winsdom.vo.CustomerBillingHeaderQueryVO;
import com.winsdom.vo.CustomerBillingHeaderUpdateVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

/**
 * <p>
 * 客户开票抬头表 服务实现类
 * </p>
 *
 * @author 
 * @since 2025-05-12
 */
@Slf4j
@Service
public class CustomerBillingHeaderServiceImpl extends ServiceImpl<CustomerBillingHeaderMapper, CustomerBillingHeader> implements ICustomerBillingHeaderService {

    private static final Logger logger = LoggerFactory.getLogger(CustomerBillingHeaderServiceImpl.class);
    @Autowired
    private CustomerBillingHeaderMapper customerBillingHeaderMapper;
    @Override
    public CustomerBillingHeader getHeder(String projectName) {
        LambdaQueryWrapper<CustomerBillingHeader> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerBillingHeader::getBuyerName, projectName);
        CustomerBillingHeader customerBillingHeader = customerBillingHeaderMapper.selectOne(queryWrapper);
        return customerBillingHeader;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateHeader(CustomerBillingHeaderUpdateVO updateVO) {
        log.info("开始更新发票抬头信息，更新信息：{}", updateVO);
        
        // 参数校验
        Assert.notNull(updateVO, "更新信息不能为空");
        Assert.notNull(updateVO.getHeaderId(), "抬头ID不能为空");

        // 查询现有配置
        CustomerBillingHeader existingHeader = getById(updateVO.getHeaderId());
        
        // 校验配置是否存在
        Assert.notNull(existingHeader, "发票抬头信息不存在");
        log.info("找到现有抬头信息：{}", existingHeader);

        // 检查来源，业主来源的抬头不能修改
        if ("业主".equals(existingHeader.getSource())) {
            throw new IllegalArgumentException("业主来源的发票抬头不能修改");
        }

        // 验证必填字段
        if (updateVO.getBuyerName() != null && updateVO.getBuyerName().trim().isEmpty()) {
            throw new IllegalArgumentException("购方名称不能为空");
        }
        if (updateVO.getTaxIdentificationNumber() != null && updateVO.getTaxIdentificationNumber().trim().isEmpty()) {
            throw new IllegalArgumentException("纳税人识别号不能为空");
        }

        // 不允许修改抬头类型，保持原有值
        existingHeader.setHeaderType(existingHeader.getHeaderType());

        // 只更新非空字段
        if (updateVO.getBuyerName() != null) {
            existingHeader.setBuyerName(updateVO.getBuyerName());
        }
        if (updateVO.getTaxIdentificationNumber() != null) {
            existingHeader.setTaxIdentificationNumber(updateVO.getTaxIdentificationNumber());
        }
        if (updateVO.getAddress() != null) {
            existingHeader.setAddress(updateVO.getAddress());
        }
        if (updateVO.getPhone() != null) {
            existingHeader.setPhone(updateVO.getPhone());
        }
        if (updateVO.getBankName() != null) {
            existingHeader.setBankName(updateVO.getBankName());
        }
        if (updateVO.getBankAccount() != null) {
            existingHeader.setBankAccount(updateVO.getBankAccount());
        }

        // 更新配置
        boolean success = updateById(existingHeader);
        log.info("更新发票抬头信息{}，更新后的信息：{}", success ? "成功" : "失败", existingHeader);
    }

    @Override
    public IPage<CustomerBillingHeaderVo> headerPageList(CustomerBillingHeaderDTO customerBillingHeaderDTO) {
        try {

            IPage<CustomerBillingHeaderVo> page = new Page<>(customerBillingHeaderDTO.getPageNo(), customerBillingHeaderDTO.getPageSize());
            IPage<CustomerBillingHeaderVo> resultPage = customerBillingHeaderMapper.headerPageList((Page<CustomerBillingHeaderVo>) page, customerBillingHeaderDTO);

            // 输出详细的查询结果到控制台
            resultPage.getRecords().forEach(record -> {
                logger.info("CustomerBillingHeaderVo: {}", record);
            });

            return resultPage;
        } catch (Exception e) {
            logger.error("Error occurred while fetching header page list", e);
            return new Page<>();
        }
    }

    @Override
    public IPage<CustomerBillingHeaderVo> header1(CustomerBillingHeaderDTO customerBillingHeaderDTO1) {
        try {

            IPage<CustomerBillingHeaderVo> page = new Page<>(customerBillingHeaderDTO1.getPageNo(), customerBillingHeaderDTO1.getPageSize());
            IPage<CustomerBillingHeaderVo> resultPage = customerBillingHeaderMapper.header1((Page<CustomerBillingHeaderVo>) page, customerBillingHeaderDTO1);

            // 输出详细的查询结果到控制台
            resultPage.getRecords().forEach(record -> {
                logger.info("CustomerBillingHeaderVo: {}", record);
            });

            return resultPage;
        } catch (Exception e) {
            logger.error("Error occurred while fetching header page list", e);
            return new Page<>();
        }
    }


    @Override
    public void updateAuditResult(CustomerBillingHeaderDTO dto) {
        customerBillingHeaderMapper.updateAuditResult(dto);
    }
    @Override
    public void updateAuditStatus(CustomerBillingHeaderDTO dto) {
        customerBillingHeaderMapper.updateAuditStatus(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createHeader(CustomerBillingHeaderCreateDTO createDTO) {
        log.info("开始创建发票抬头，创建信息：{}", createDTO);
        
        // 参数校验
        Assert.notNull(createDTO, "创建信息不能为空");
        Assert.notNull(createDTO.getCustomerId(), "客户ID不能为空");
        Assert.notNull(createDTO.getSource(), "来源不能为空");
        Assert.notNull(createDTO.getHeaderType(), "抬头类型不能为空");
        Assert.hasText(createDTO.getBuyerName(), "购方名称不能为空");

        // 创建实体
        CustomerBillingHeader header = new CustomerBillingHeader();
        header.setCustomerId(createDTO.getCustomerId());
        header.setSource(createDTO.getSource());
        header.setHeaderType(createDTO.getHeaderType());
        header.setBuyerName(createDTO.getBuyerName());
        header.setTaxIdentificationNumber(createDTO.getTaxIdentificationNumber());
        header.setAddress(createDTO.getAddress());
        header.setPhone(createDTO.getPhone());
        header.setBankName(createDTO.getBankName());
        header.setBankAccount(createDTO.getBankAccount());

        // 根据来源设置状态
        if ("业主".equals(createDTO.getSource())) {
            header.setAuditStatus(0);  // 待审核
            header.setStatus(0);       // 禁用
            header.setAuditResult(null); // 审核结果为空
        } else if ("平台".equals(createDTO.getSource())) {
            header.setAuditStatus(1);  // 审核通过
            header.setStatus(1);       // 启用
            header.setAuditResult(1);  // 审核通过
        } else {
            throw new IllegalArgumentException("来源只能是'平台'或'业主'");
        }

        // 保存数据
        boolean success = save(header);
        log.info("创建发票抬头{}，创建后的信息：{}", success ? "成功" : "失败", header);
        
        return header.getHeaderId();
    }

    @Override
    public List<CustomerBillingHeaderQueryVO> getHeadersByCustomerId(Long customerId) {
        Assert.notNull(customerId, "客户ID不能为空");
        return baseMapper.selectHeadersByCustomerId(customerId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void toggleHeaderStatus(Long headerId) {
        log.info("开始切换发票抬头状态，抬头ID：{}", headerId);
        
        // 参数校验
        Assert.notNull(headerId, "抬头ID不能为空");

        // 查询现有配置
        CustomerBillingHeader existingHeader = getById(headerId);
        
        // 校验配置是否存在
        Assert.notNull(existingHeader, "发票抬头信息不存在");
        log.info("找到现有抬头信息：{}", existingHeader);

        // 检查来源，业主来源的抬头不能修改
        if ("业主".equals(existingHeader.getSource())) {
            throw new IllegalArgumentException("业主来源的发票抬头不能修改状态");
        }

        // 切换状态（0变1，1变0）
        existingHeader.setStatus(existingHeader.getStatus() == 0 ? 1 : 0);
        boolean success = updateById(existingHeader);
        log.info("切换发票抬头状态{}，更新后的信息：{}", success ? "成功" : "失败", existingHeader);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHeader(Long headerId) {
        log.info("开始删除发票抬头，抬头ID：{}", headerId);
        
        // 参数校验
        Assert.notNull(headerId, "抬头ID不能为空");

        // 查询现有配置
        CustomerBillingHeader existingHeader = getById(headerId);
        
        // 校验配置是否存在
        Assert.notNull(existingHeader, "发票抬头信息不存在");
        log.info("找到现有抬头信息：{}", existingHeader);

        // 检查来源，业主来源的抬头不能删除
        if ("业主".equals(existingHeader.getSource())) {
            throw new IllegalArgumentException("业主来源的发票抬头不能删除");
        }

        // 删除抬头
        boolean success = removeById(headerId);
        log.info("删除发票抬头{}，抬头ID：{}", success ? "成功" : "失败", headerId);
    }
}
